package business

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"h_rpcx/serve/user/basics"
	"time"
)

type ServiceContext struct {
	DB *gorm.DB
}

func NewServiceContext() *ServiceContext {
	sprintf := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=%v&parseTime=True&loc=Local",
		basics.MysqlS.Username, basics.MysqlS.Password, basics.MysqlS.Host, basics.MysqlS.Port,
		basics.MysqlS.DataBase, basics.MysqlS.CharSet)
	db, err := gorm.Open(mysql.Open(sprintf), &gorm.Config{})
	s, _ := db.DB()
	s.SetMaxOpenConns(200)
	s.SetMaxIdleConns(100)
	s.SetConnMaxLifetime(1 * time.Hour)
	s.SetConnMaxLifetime(30 * time.Second)
	if err != nil {
		panic("数据库连接出错：" + err.Error())
	}
	//log.Printf("数据库连接成功")
	return &ServiceContext{
		DB: db,
	}
}
